package com.cp.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Des:
 * Redis的值 进行序列化和反序列
 *
 * @author XL
 * @Date 2022/2/16 18:14
 */
public class CpRedisJsonSerializer<T> implements RedisSerializer<T> {


    static {
        //打开autoType功能
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    }

    public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
    private final Class<T> clazz;


    public CpRedisJsonSerializer(Class<T> clazz) {
        this.clazz = clazz;
    }

    /**
     * des:
     * 序列化
     *
     * @param t 操作对象
     * @return {@link byte[] }
     * @author captain
     * @date 2022/2/16 18:15
     */
    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName, SerializerFeature.WriteDateUseDateFormat).getBytes(DEFAULT_CHARSET);
    }

    /**
     * des:
     * 反序列化 将字节数组 - > 对象
     *
     * @param bytes 字节数组
     * @return {@link Object }
     * @author captain
     * @date 2022/2/16 18:16
     */
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        return JSON.parseObject(str, clazz);
    }
}
